package com.fs.controller;

import com.fs.annotation.SysLog;
import com.fs.pojo.SysAdmin;
import com.fs.service.ShiroService;
import com.fs.service.SysAdminService;
import com.fs.vo.SysResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Api(tags = "登陆管理")
@RestController
@RequestMapping("/comm")
public class AdminLoginController {

    @Autowired
    private SysAdminService adminService;

    @Autowired
    private ShiroService shiroService;

    /**
     * admin登陆
     * @param admin 账户、密码、验证码、验证码id
     * @return
     */
//    @SysLog("登陆")
    @ApiOperation(value = "登陆", notes = "参数:用户名 密码 验证码 UUID")
    @PostMapping("/adminLogin")
    public SysResult adminDoLogin(@RequestBody SysAdmin admin){
        return adminService.doLogin(admin);
    }


//    @GetMapping("/adminCaption")
//    public ResultVO getCaption(){
//        return adminService.getCaption();
//    }

    /**
     * 验证码
     */
    @ApiOperation(value = "获取验证码")
    @GetMapping("captcha.jpg")
    public SysResult captchaJpg()throws IOException {
        String uuid= UUID.randomUUID().toString();
        BufferedImage image = adminService.getCaptcha(uuid);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
        ImageIO.write(image, "jpg", baos);//写入流中
        BASE64Encoder encoder = new BASE64Encoder();
        byte[] bytes = baos.toByteArray();//转换成字节
        String png_base64 = encoder.encodeBuffer(bytes).trim();//转换成base64串
        png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n

        HashMap<String, String> map = new HashMap<>();
        map.put("uuid",uuid);
        map.put("img","data:image/jpg;base64,"+png_base64);

        return SysResult.success(map);
    }

    /**
     * 退出
     */
//    @SysLog("退出")
    @ApiOperation(value = "退出", notes = "参数:token")
    @PostMapping("/logout")
    public SysResult logout(@RequestHeader("token")String token) {
        SysResult result = new SysResult();
        shiroService.logout(token);
        result.setStatus(200).setMsg("您已安全退出系统");
        return result;
    }
}
